package top.truism.auth.permission;

import org.springframework.stereotype.Component;
import top.truism.auth.common.LocalUser;
import top.truism.auth.enums.UserLevel;
import top.truism.auth.util.MockUtil;
import top.truism.auth.web.pojo.Permission;
import top.truism.auth.web.pojo.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class AuthorizeVerifyResolverImpl implements AuthorizeVerifyResolver {

  @Override
  public boolean handleLogin(HttpServletRequest request, HttpServletResponse response, MetaInfo metaInfo) {
    // 校验Token
    System.out.println("-----Token校验-----");
    // 登陆设置当前发起请求的用户
    LocalUser.setLocalUser(new User("admin2", "admin2"));
    return true;
  }

  /**
   * 自定义分组需要自定义权限
   *
   * @param request
   * @param response
   * @param metaInfo
   * @return
   */
  @Override
  public boolean handleGroup(HttpServletRequest request, HttpServletResponse response, MetaInfo metaInfo) {
    handleLogin(request, response, metaInfo);
    // 校验权限
    UserLevel userLevel = metaInfo.getUserLevel();
    String module = metaInfo.getModule();
    String permission = metaInfo.getPermission();
    List<Permission> permissions = MockUtil.createPermissions();
    boolean isMatched = permissions.stream().anyMatch(p -> p.getModule().equals(module) && p.getName().equals(permission) && p.isMount() && userLevel == UserLevel.Group);
    if(!isMatched) {
      throw new UnsupportedOperationException("权限不足!");
    }
    return true;
  }

  /**
   * 超级管理员拥有所有权限
   * @param request
   * @param response
   * @param metaInfo
   * @return
   */
  @Override
  public boolean handleAdmin(HttpServletRequest request, HttpServletResponse response, MetaInfo metaInfo) {
    handleLogin(request, response, metaInfo);
    // 校验权限
    User user = LocalUser.getLocalUser();
    boolean isAdmin = MockUtil.isLogin(user);
    if(!isAdmin) {
      throw new UnsupportedOperationException("非管理员!");
    }
    return true;
  }

  @Override
  public boolean handleNoyHandlerMethod(HttpServletRequest request, HttpServletResponse response, MetaInfo metaInfo) {
    return true;
  }

  @Override
  public void handleAfterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
    // 请求结束移除用户
    LocalUser.removeLocalUser();
  }
}
